/********************************************************************************
 * Project Name		[JavaEE_JDBC]
 * File Name     	[GetReturnedPrimaryKey.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import org.junit.Test;

import utils.jdbc.JdbcUtils;

/**
 * java.sql.PreparedStatement
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class GetReturnedPrimaryKey {

	/**
	 * 当主键方式是自动生成时, 获取刚刚生成的主键值
	 */
	@Test
	public void testGetPrimaryKey() {
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;

		String sql = "INSERT INTO user(username, password, age, gender, birthday) VALUES(?, ?, ?, ?, ?)";
		try {
			connection = JdbcUtils.getInstance().getConnection();
			// 指定Statement.RETURN_GENERATED_KEYS来得到生成的主键
			statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			statement.setString(1, "U1");
			statement.setString(2, "12345");
			statement.setInt(3, 30);
			statement.setString(4, "F");
			statement.setDate(5, new java.sql.Date(new java.util.Date().getTime()));
			statement.executeUpdate();

			// 获得新生成的记录的主键值的ResultSet对象
			resultSet = statement.getGeneratedKeys();
			if (resultSet.next()) {
				System.out.println("Primary Key = " + resultSet.getObject(1));
			}

			// 在ResultSet中只有一列: GENERATED_KEY, 用于存放新生成的主键
			ResultSetMetaData metaData = resultSet.getMetaData();
			for (int i = 0; i < metaData.getColumnCount(); i++) {
				System.out.println(metaData.getColumnName(i + 1));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
